<script setup lang='ts'>
import { ref } from 'vue';


defineProps({
  line: {
    type: Boolean,
    default: true
  },
  max: {
    type: Number,
    default: 90
  },
})

const startDis = ref(0)
const endDis = ref(0)

const ceil = ref(false)
const middle = ref(false)
const floor = ref(false)


function handleTouchStart(e: TouchEvent) {
  startDis.value = e.touches[0].clientY
}

const content = ref<{ $el: HTMLElement } | null>(null)

function handleTouchEnd(e: TouchEvent) {
  endDis.value = e.changedTouches[0].clientY
  if (endDis.value - startDis.value > 50) {
    if (ceil.value) {
      // 下拉
      const dom = content.value!.$el as HTMLElement
      if (dom.scrollTop === 0) {
        ceil.value = false
      }
    } else {
      floor.value = true
    }

  } else if (startDis.value - endDis.value > 50) {
    // 上拉
    if (floor.value) {
      floor.value = false
    } else {
      ceil.value = true
    }
  }
}

function handleClickLine() {
  if (ceil.value) {
    ceil.value = false
    floor.value = true
  } else if (floor.value) {
    floor.value = false
    ceil.value = true
  }
}

const emits = defineEmits(['opened'/* 打开之后的回调事件 */, 'closed'/* 打开之后的回调事件 */])

defineExpose({
  /**
   * 打开弹窗
   */
  open() {
    ceil.value = false
    floor.value = false
    middle.value = true

    emits('opened')
  },
  /**
   * 最小化弹窗
   */
  close() {
    ceil.value = false
    floor.value = false
    middle.value = false

    emits('closed')
  }
})

</script>

<template>
  <div class='popup-flex__container' :class="{ ceil, floor, middle }" @touchstart="handleTouchStart"
    @touchend="handleTouchEnd">
    <!-- 顶部的线条 -->
    <view class="popup-flex__line" v-if="line" @click="handleClickLine"></view>
    <!-- 头部 -->
    <view class="popup-flex__header" v-if="$slots.header">
      <slot name="header"></slot>
    </view>
    <view ref="content" class="popup-flex__content">
      <slot></slot>
    </view>
  </div>
</template>

<style scoped lang='scss'>
@import "./popupFlex.scss";
</style>